<template>
  <header class="sp-header">
    <!-- <div>12312312</div> -->
    <h1 class="sp-header__logo"></h1>
    <span class="sp-header__avatar" v-if="token" @click="setMemberStatus">
      <img :src="userInfo.avatar"/>
    </span>
    <span class="sp-header__name" v-if="token">{{ userInfo.nickname }}</span>
    <el-tooltip effect="dark" content="设置" placement="bottom"  v-if="token">
      <span class="sp-header__action">
        <i class="el-icon-setting"></i>
      </span>
    </el-tooltip>
    <!-- <span v-if="!token"  class="sp-header__login">登录</span> -->
    <!-- <a href="http://oa.xngjgg.cn/pc-weixin"  v-if="!token"  class="sp-header__login" target="_self">登录</a> -->
    <span  v-if="!token"  class="sp-header__login" @click="login">登录</span>
    <el-tooltip effect="dark" content="退出" v-else placement="bottom">
      <span class="sp-header__action" @click="exit()">
        <i class="el-icon-switch-button"></i>
      </span>
    </el-tooltip>
    <!-- 个人中心弹框 -->
    <div class="dw-member" v-if="memberStatus">
      <ul class="dw-member__header">
        <li @click="setMemberIndex(0)" :class="{ active: memberIndex === 0 }">已选线路</li>
        <li @click="setMemberIndex(1)" :class="{ active: memberIndex === 1 }">个人中心</li>
      </ul>
      <div class="dw-member__content">
        <div class="dw-member__point" v-show="memberIndex === 0">
          <div class="dw-member__point-head">
            <el-input placeholder="批量增加车辆" class="dw-member__point-input" v-model="codes" />
            <el-button type="primary" class="dw-member__point-submit" @click="addCheckList">批量增加车辆</el-button>
          </div>
          <div class="dw-member__point-body">
            <template v-if="check && check.length">
             <div  v-for="(item, $index) in check" :key="$index">
                <div class="dw-member__point-item"  v-for="(cars,index) in item.cars" :key="index">
                <div class="dw-member__point-pics">
                  <img  :src="`http://oa.xngjgg.cn${cars.thumb}`" alt="">
                </div>
                <div class="dw-member__point-info">
                  <h3 v-if="item.route_name && item.route_name">{{ item.route_name }}</h3>
                  <p v-if="cars.code && cars.code">车号: {{cars.code }}</p>
                  <p v-if="item.billboard && item.billboard.code">编号: {{ item.billboard.code }}</p>
                  <i class="el-icon-delete" v-if="cars && cars.id" @click="delCheckList(cars.id)"></i>
                </div>
              </div>
             </div>
            </template>
            <template v-else>
              <div style="padding: 50px; text-align: center;">
                暂无数据
              </div>
            </template>
          </div>
          <div class="dw-member__point-foot">
            <!-- <div class="dw-member__point-page">
              <a-pagination
                :defaultCurrent="queryParams.page"
                :total="total"
                @change="getPageCurrent"
                @showSizeChange="getPageSize"
              />
            </div> -->
            <div class="dw-member__point-control">
              <el-button class="a-button" @click="clearCheckList(false)">一键清空</el-button>
              <el-button class="a-button" type="primary" @click="setLists">生成车辆订单</el-button>
            </div>
          </div>
        </div>
        <div class="dw-member__lists" v-show="memberIndex === 1">
          <template v-if="lists && lists.length">
            <div class="dw-member__lists-item" v-for="(item, $index) in lists" :key="$index">
              <div class="dw-member__lists-name">
                <h2 @click="getPointInfo(item.id)">
                  <span v-if="!item.edit">{{ item.name }}-{{item.user_name}}({{ item.point_num }})</span>
                  <input v-else type="text" v-model="item.name">
                </h2>
                <div class="dw-member__lists-control">
                  <a @click="updateDateModal(item)">修改</a>
                  <a @click="setDateModal($index)">预约</a>
                  <a @click="setShare(item.id)">分享</a>
                  <a :href="`http://oa.xngjgg.cn/api/bus/user/car/export?user_bus_car_id=${item.id}`">导出</a>
                </div>
              </div>
              <div class="dw-member__lists-foot">
                <span>生成时间: {{ item.created_at }}</span>
                <!-- <a-icon v-if="item.edit" type="save" @click="setListsName($index)" /> -->
                <!-- <a-icon v-else type="form" @click="setListsEdit($index)" /> -->
                <i class="el-icon-edit active" v-if="item.edit"  @click="setListsName($index)"></i>
                <i class="el-icon-folder action" v-else @click="setListsEdit($index)"></i>
                <i class="el-icon-delete action" @click="delLists($index)"></i>
                <!-- <a-popconfirm title="是否删除？" @confirm="delLists($index)">
                  <a-icon type="delete" />
                </a-popconfirm> -->
              </div>
            </div>
          </template>
          <template v-else>
            <div style="padding: 50px; text-align: center;">
              暂无数据
            </div>
          </template>
        </div>
      </div>
    </div>
    <!-- 列表 -->
    <sp-dialog :visible="listsInfoStatus" width="600px" title="线路详情" @cancel="listsInfoStatus = false" @submit="listsInfoStatus = false">
      <template v-if="listsInfo && listsInfo.length">
        <div class="dw-member__point-item" v-for="(item, $index) in listsInfo" :key="$index">
          <div class="dw-member__point-pics">
            <img v-if="item.thumb" :src="`http://oa.xngjgg.cn/${item.thumb}`" alt="">
          </div>
          <div class="dw-member__point-info">
            <!-- <h3>{{ item.title }}</h3> -->
            <p>路线: {{ item.route.route_name}}</p>
            <p>车号: {{ item.code }}</p>
          </div>
        </div>
      </template>
      <template v-else>
        <div>
          暂无数据
        </div>
      </template>
    </sp-dialog>
    <!-- 预约 -->
    <el-dialog title="预约时间" :visible.sync="bookingStatus" width="500px">
      <el-form :model="booking" :rules="bookingRules">
        <el-form-item label="客户姓名" prop="name">
          <el-input style="width: 350px" v-model="booking.name" />
        </el-form-item>
        <el-form-item label="预约时间" prop="date">
           <!-- <el-date-picker
      v-model="booking.date"
      type="datetimerange"
      :picker-options="bookingOptions"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      value-format="yyyy-MM-dd"
      align="right">
    </el-date-picker> -->
          <el-date-picker
            v-model="booking.date"
            type="daterange"
            align="left"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="bookingOptions">
          </el-date-picker>
        </el-form-item>
      </el-form>
       <div slot="footer" class="dialog-footer">
    <el-button @click="bookingStatus = false">取 消</el-button>
    <el-button type="primary" @click="dateSubmit">确 定</el-button>
  </div>
</el-dialog>
    <!-- <sp-dialog :visible="bookingStatus" @submit="dateSubmit" width="460px" title="预约"> -->
    <!-- </sp-dialog> -->
    <!-- 分享 -->
    <!-- <sp-dialog :visible="listsInfoStatus"></sp-dialog> -->
  </header>
</template>

<script>
import { getUrlParam } from '@/utils/domUtils.js'
import { getUser } from '@/api/oa/index.js'
import { getUserInfo, getMemberLists, getCheckList, delCheckList, addCheckList, clearCheckList, setMemberLists, getPointInfo, delMemberLists, setBooking } from '@/api/map'
import { setMulFavorite, getUserCar, getCarSave, getCardel, setMemberName } from '@/api/bus'

export default {
  name: 'SpHeader',
  props: {},
  components: {},
  data () {
    return {
      userInfo: {},
      token: window.localStorage.getItem('token'),
      memberStatus: false,
      memberIndex: 0,
      // mem
      codes: '',
      check: [],
      // lists
      lists: [],
      listsInfo: {},
      listsInfoStatus: false,
      bookingRules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        date: [
          { required: true }
        ]
      },
      bookingOptions: {
        shortcuts: [{
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [end, start])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() + 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [end, start])
          }
        }, {
          text: '最近六个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() + 3600 * 1000 * 24 * 180)
            picker.$emit('pick', [end, start])
          }
        }, {
          text: '最近一年',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() + 3600 * 1000 * 24 * 365)
            picker.$emit('pick', [end, start])
          }
        }]
      },
      bookingStatus: false,
      booking: {
        name: '',
        date: []
      }
    }
  },
  created () {},
  mounted () {
    const token = window.localStorage.getItem('token')
    this.getLogin()
    if (token === null || !token) {
      window.localStorage.clear()
    }
    // this.getCode()
    this.getCheckList()
  },
  destroyed () {},
  methods: {
    async getLogin () {
      // const code = window.location.search.split('=')[1]
      const r = Math.random()
      const { data } = await getUserInfo(r)
      this.userInfo = data || JSON.parse(window.localStorage.getItem('userInfo'))
      // window.localStorage.setItem('userInfo', JSON.stringify(data))
      // window.localStorage.setItem('token', code)
      // window.location.href = window.location.origin + window.location.pathname
    },
    login () {
      window.location.href = 'http://oa.xngjgg.cn/pc-weixin'
    },
    async setCheckGroup (codes) {
      const params = {
        bus_car_codes: codes
      }
      const { status } = await setMulFavorite(params)
      this.$notify[status ? 'success' : 'error']({
        title: status ? '成功' : '错误',
        message: status ? '请回到已选线路修改路线' : '修改失败'
      })
      this.getCheckList()
      // this.$parent.$parent.$parent.$parent.$children[1].$children[0].$children[0].getCheckList()
    },
    updateDateModal (item) {
      console.log(item.car_codes)
      this.clearCheckList(true)
      this.setCheckGroup(item.car_codes)
    },
    getCode () {
      const code = getUrlParam('code')
      if (!code) {
        return false
      }
      console.log(code)
      const params = {
        openid: code
      }
      getUser(params).then(res => {
        const { status, data } = res
        if (status) {
          this.userInfo = data
          this.token = data.api_token
          window.localStorage.setItem('userInfo', JSON.stringify(data))
          window.localStorage.setItem('token', data.api_token)
          // this.$router.go(0)
        }
      })
    },
    exit () {
      this.token = ''
      window.localStorage.clear()
      this.$router.push({ name: 'pointMap' })
      // window.location.reload()
    },
    setMemberIndex (index) {
      this.memberIndex = index
      // if (index === 1) {
      //   this.getLists()
      // } else {
      //   this.getCheckList()
      // }
    },
    setMemberStatus () {
      this.memberStatus = !this.memberStatus
      this.getLists()
      this.getCheckList()
    },
    // 已选点位
    // 清空已选点位
    async clearCheckList (fag) {
      const { status } = await clearCheckList()
      if (status) {
        this.check = []
        if (fag) return
        this.$notification.success({
          message: '删除成功'
        })
      } else {
        this.$notification.error({
          message: '删除失败'
        })
      }
    },
    // 批量添加点位
    async addCheckList () {
      const params = {
        bus_car_codes: this.codes
      }
      const { status } = await setMulFavorite(params)
      if (status) {
        this.getCheckList()
        this.codes = ''
        this.$notification.success({
          message: '新增成功'
        })
      } else {
        this.$notification.error({
          message: '新增失败'
        })
      }
    },
    // 获取已选择点位
    async getCheckList () {
      const { data } = await getCheckList()
      this.total = data.total
      this.check = data
    },
    // 删除已选点位
    async delCheckList (id) {
      const params = {
        bus_car_id: id
      }
      const { status } = await delCheckList(params)
      if (status) {
        this.getCheckList()
        // this.clearCheckList()
        this.$notification.success({
          message: '删除成功'
        })
      } else {
        this.$notification.error({
          message: '删除失败'
        })
      }
    },
    // 生成点位图
    async setLists () {
      // console.log(this.check)
      const reslist = []
      this.check.forEach((item) => {
        item.cars.forEach(itemcar => {
          // console.log(itemcar)
          reslist.push(itemcar.code)
        })
      })
      // console.log(reslist.toString())
      const date = new Date()
      const name = date.getFullYear() + '-' + (date.getMonth() + 1) + date.getDay()
      // console.log(name)
      const params = {
        name,
        car_codes: reslist.toString()
      }
      const { status } = await getCarSave(params)
      if (status) {
        this.getLists()
        this.getCheckList()
        this.$notification.success({
          message: '添加成功'
        })
      } else {
        this.$notification.error({
          message: '添加失败'
        })
      }
      // this.clearMarkerGroup()
    },
    // // 清空地图的已选点位
    // clearMarkerGroup () {
    //   this.$parent.$parent.$children[1].markGroup = []
    //   this.$parent.$parent.$children[1].map.remove(this.$parent.$parent.$children[1].markGroup)
    // },
    // 个人中心
    // 获取个人中心的一保存点位
    async getLists () {
      const { data } = await getUserCar()
      this.lists = data.data && data.data.map(item => {
        item.edit = false
        return item
      })
      console.log(this.lists)
    },
    // 删除点位列表
    async delLists (index) {
      const { status } = await getCardel({ id: this.lists[index].id })
      if (status) {
        this.$notification.success({
          message: '删除成功'
        })
      } else {
        this.$notification.error({
          message: '删除失败'
        })
      }
      this.getLists()
    },
    // 获取单位详情
    async getPointInfo (id) {
      const { data } = await getPointInfo(id)
      this.listsInfo = data
      this.listsInfoStatus = true
    },
    // 编辑点位列表名称
    setListsEdit (index) {
      this.lists[index].edit = true
    },
    // 修改点位列表名称
    async setListsName (index) {
      const item = this.lists[index]
      const params = {
        id: item.id,
        name: item.name
      }
      const { status } = await setMemberName(params)
      if (status) {
        this.lists[index].edit = false
        this.$notification.success({
          message: '修改成功'
        })
      } else {
        this.$notification.error({
          message: '修改失败'
        })
      }
    },
    // 分享
    setShare (id) {
      // this.$router.push({
      //   path: '/share',
      //   query: {
      //     id
      //   }
      // })
      const origin = window.location.origin
      window.open(origin + '/teadmedia/#/share?id=' + id)
    },
    // 打开预约弹窗
    setDateModal (index) {
      this.bookingIndex = index
      this.bookingStatus = true
    },
    async dateSubmit () {
      if (this.booking.name === '') {
        this.$notification.error({
          message: '客户姓名不能为空'
        })
        return false
      }
      const params = {
        begin_date: this.booking.date[0],
        end_date: this.booking.date[1],
        customer: this.booking.name,
        user_bus_car_id: this.lists[this.bookingIndex].id
      }
      console.log(this.booking.date)
      const { status } = await setBooking(params)
      if (status) {
        this.bookingStatus = false
        this.$notification.success({
          message: '预约成功'
        })
      } else {
        this.$notification.error({
          message: '预约失败'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  ul,
  li {
    padding: 0;
    margin: 0;
    list-style: none;
  }
  .sp-header {
    position: relative;
    text-align: right;
    height: 58px;
    background: #fff;
    box-shadow: 0 1px 4px hsla(0,0%,88.2%,.5);

    span {
      display: inline-block;
      vertical-align: middle;
      cursor: pointer;
      img {
        width:100%;
        object-fit: cover;
        border-radius: 50%;
      }
      &:not(.sp-header__avatar) {
        height: 100%;
        line-height: 58px;
      }
    }

    .sp-header {

      &__ {

        &logo {
          position: absolute;
          top: 50%;
          left: 0;
          transform: translateY(-50%);
          margin: 0;
          width: 300px;
          height: 58px;
          font-size: 0;
          background: #fff;
          // margin-bottom: 10px;

          &:after {
            content: '';
            position: absolute;
            top: 50%;
            left: 70px;
            transform: translate(-50%, -50%);
            width: 300px;
            height: 40px;
            background: #fff url('../../assets/images/logo2.png') left center no-repeat;
            background-size: auto 40px;
          }
        }

        &avatar {
          width: 32px;
          height: 32px;
          line-height: 32px;
          margin-right: 15px;
          background: #00abeb;
          border-radius: 50%;
          color: #fff;
          text-align: center;
        }

        &name {
          margin-right: 15px;
        }
        &login {
          height: 100%;
          line-height: 58px;
          padding-right:20px;
        }
        &action {
          position: relative;
          width: 48px;
          text-align: center;
          font-size: 16px;
          color: #999;

          &:after {
            content: '';
            position: absolute;
            left: 0;
            top: 23px;
            height: 12px;
            width: 1px;
            background: #eee;
          }
        }
      }
    }
  }

  .dw-member {
    position: absolute;
    top: 58px;
    z-index: 111;
    right: 10px;
    width: 320px;
    height: 600px;
    overflow: auto;
    background: #fff;
    box-shadow: 0 0 10px 4px rgba(0, 0, 0, .05);

    &__content {
      height: 530px;
    }

    &__header {
      height: 50px;
      line-height: 50px;
      display: flex;
      align-items: center;
      text-align: center;
      margin-bottom: 0;
    }

    &__header li {
      position: relative;
      flex: 1;
      height: 100%;
      background: #455bab;
      color: #fff;
      font-size: 18px;
      font-weight: bold;
      transition: all .3s;

      &.active {
        background: #4f6ede;

        &:after {
          content: '';
          position: absolute;
          left: 50%;
          bottom: 0;
          transform: translateX(-50%);
          width: 0;
          height: 0;
          border: solid 6px;
          border-color: transparent transparent #fff transparent;
        }
      }
    }

    &__lists {
      padding: 0 15px 10px;
      text-align: left;

      &-item {
        padding: 10px 0;
        border-bottom: 1px dashed #ccc;
        span {
          line-height: 22px !important;
        }
      }

      &-name {
        display: flex;
        line-height: 22px;
        h2 {
          flex: 1;
          font-size: 12px;
          margin: 0;
          font-weight: normal;
        }
        & > div {
          a {
            font-size: 12px;
            color: #4f6ede;
            padding: 0 0 0 10px;
          }
        }
      }

      &-foot {
        display: flex;
        font-size: 12px;
        line-height: 22px;
        padding: 5px 0 0;

        span {
          flex: 1;
        }

        .action {
          line-height: 22px;
          padding-left: 10px;
          cursor: pointer;
          font-size: 14px;
          margin-left: 10px;
        }
      }
    }

    &__point {
      display: flex;
      flex-direction: column;
      padding: 10px;
      height: 100%;

      &-head {
        display: flex;
        margin-bottom: 10px;

        .dw-member__point-input {
          flex: 1;
          margin-right: 15px;
        }
      }

      &-body {
        padding-top: 5px;
        flex: 1;
        overflow: auto;
        height: 100%;
      }

      &-item {
        display: flex;
        align-items: flex-start;
      }

      &-pics {
        position: relative;
        width: 80px;
        height: 60px;
        border: 1px dashed #eee;
        margin-bottom: 10px;

        img{
          width: 100%;
          height: 100%;
        }
      }

      &-info {
        position: relative;
        flex: 1;
        width: 200px;
        padding-left: 10px;
        text-align: left;

        .el-icon-delete {
          position: absolute;
          top: 0;
          right: 0;
        }

        p,
        h3 {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        p {
          font-size: 12px;
          line-height: 20px;
          margin: 0;
          color: #666;
        }

        h3 {
          font-size: 14px;
          color: #4f6ede;
          margin-bottom: 12px;
          line-height: 1;
        }

        .icon-del {
          position: absolute;
          right: 0;
          bottom: 0;
        }
      }

      &-foot {
      }

      &-page {
        padding: 10px 0 20px;
      }

      &-control {
        display: flex;

        .a-button {
          flex: 1;

          &:first-child {
            margin-right: 10px;
          }
        }
      }
    }
  }
</style>
